package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.commen.R;
import com.itheima.dto.Roles;
import com.itheima.dto.UserDto;
import com.itheima.mapper.PermissionGroupMapper;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.PermissionPermissionGroupMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.PermissionGroup;
import com.itheima.pojo.User;
import com.itheima.service.FrameService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
@Transactional  //开启事务
public class FrameServiceImpl extends ServiceImpl<UserMapper, User> implements FrameService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionPermissionGroupMapper permissionPermissionGroupMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private PermissionGroupMapper permissionGroupMapper;

    //用户登录
    @Override
    public R login(String username, String password) {
        //1.校验参数是否存在
        if (username == null || password == null) {
            return R.error("参数非法");
        }
        //1.1将页面提交的密码进行md5加密处理,得到加密后的字符串
        //String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        String pwd =password;//为了进前端页面暂时数据
        //2.根据页面提交的用户名查询数据库中员工数据信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, username);
        User user = this.getOne(wrapper);
        //2.1如果没有查询到,则返回登录失败结果
        if (user == null) {
            return R.error("用户不存在");
        }
        //3.密码比对,如果不一致,则返回登陆失败结果
        if (!user.getPassword().equals(pwd)) {
            return R.error("ser登陆失败");
        }
        //4.查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if (user.getStatus() != 0) {
            return R.error("账号已禁用");
        }
        //5.登录成功,将员工id存入session,并返回登录成功结果
        return R.success(user);
    }

    //用户注册
    @Override
    public void register(String username, String password) {
        /*//查询数据库中是否已有该用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, username);
        User user = this.getOne(wrapper);
        //数据库中已经有这个用户
        if (user != null) {
            return R.error("账号已存在");
        }*/
        //数据库中新增新用户,为新用户补全参数
        User u = new User();
        u.setEmail(username);
        u.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        u.setPermissionGroupId(3L);  //默认权限为编辑组
        u.setRole("editor");  //默认角色为编辑
        u.setSex("男");//性别默认为男
        u.setCreateTime(new Date());
        u.setLastUpdateTime(new Date());

        log.info("u.getEmail--"+u.getEmail());
        log.info("u.getpwd"+u.getPassword());
        //将新用户注册进数据库
        userMapper.insert(u);
        log.info("添加用户成功");
    }

    //用户修改密码
    @Override
    public void password(String oldPassword, String newPassword) {
        //将页面提交的密码进行md5加密处理,得到加密后的字符串
        String oldPwd = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        String newPwd = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        //通过原密码找到数据库中对应的user的数据信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPassword,oldPwd);
        User user = this.getOne(wrapper);
        //原密码对应的用户不存在
        /*if (user==null){
            return R.error("用户不存在");
        }*/
        log.info("用户存在");
        //用户存在,修改对应的密码
        user.setPassword(newPwd);
        user.setLastUpdateTime(new Date());
        this.updateById(user);
        log.info("修改密码成功");
    }

    //用户资料
    @Override
    public UserDto profile(Long userId) {
        User user = userMapper.selectById(userId);
        if (user==null) {
            log.info("该用户不存在");
            return null;
        }
//        UserDto userDto = new UserDto();
        String jsonString = JSON.toJSONString(user);
        UserDto userDto = JSON.parseObject(jsonString, UserDto.class);
        userDto.setName(user.getUsername());
        userDto.setIntroduction(user.getIntroduction());
        userDto.setAvatar(user.getAvatar());

        PermissionGroup permissionGroup = permissionGroupMapper.selectById(user.getPermissionGroupId());
        userDto.setGroup(permissionGroup.getTitle());

        //在a_permission_permission_group  通过user.getPermissionGroupId()获取pid
        List<Long> permissionIds = permissionPermissionGroupMapper.selectByPgid(user.getPermissionGroupId());
        log.info("权限id====="+permissionIds.toString());
        //获取符合条件的permission
        List<Permission> permissions = permissionMapper.selectBatchIds(permissionIds);

        Roles roles = new Roles();
        List<String> menus =new ArrayList<>();
        List<String> points=new ArrayList<>();
        for (Permission permission : permissions) {
            String menu = permissionMapper.selectGetMenus(permission.getId());
            if (null!=menu) menus.add(menu);

            String point = permissionMapper.selectGetPoints(permission.getId());
            if (point!=null) points.add(point);
        }
        roles.setMenus(menus);
        roles.setPoints(points);
        userDto.setRoles(roles);
        userDto.setPermission_group_id(userDto.getPermissionGroupId());
        log.info("userDto.toString()==="+userDto.toString());
        return userDto;
    }
}
